from datetime import datetime
from .BaseConvert import Convert


class DatetimeConvert(Convert):
    field_type = 'datetime'
    date_format = "%Y-%m-%d %H:%M:%S"

    @classmethod
    def to_read(cls, rec, field, **kwargs):
        return rec[field.name].strftime(cls.date_format) if rec[field.name] else ""

    @classmethod
    def to_field(cls, value, metadata=None,update=False):
        if isinstance(value, str):
            return datetime.strptime(value, cls.date_format)
        elif isinstance(value, datetime):
            return value

    @classmethod
    def to_domain(cls, field, value, **kwargs):
        if isinstance(value, str):
            try:
                value = datetime.strptime(value, cls.date_format)
                return [(field.name, '=', value)]
            except ValueError:
                raise ValueError('Incorrect data format, should be YYYY-MM-DD HH:MM:SS')
        elif isinstance(value, datetime):
            return [(field.name, '=', value)]
